package com.uinnova.product.eam.workable.rsm;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.HttpMethod;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.*;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

@Slf4j
public class AliyunObsRsmBehavior extends RsmOperationInfo implements RsmBehavior{

    private static AmazonS3 s3ObsClient;

    public AliyunObsRsmBehavior(String endPoint, String accessKey, String secretKey, String bucketName, Long urlExpireSeconds,String region , String isHttps) {
        this.endpoint = endPoint;
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.bucketName = bucketName;
        this.urlExpireSeconds = urlExpireSeconds;
        this.region = region;
        this.isHttps = isHttps;
        initClient();
    }

    /**
     * 初始化阿里oss客户端
     */
    @Override
    public void initClient() {
        if (this.s3ObsClient == null) {
           AwsClientBuilder.EndpointConfiguration endpointConfiguration =
                   new AwsClientBuilder.EndpointConfiguration(this.endpoint,this.region);
            AWSCredentials credentials = new BasicAWSCredentials(this.accessKey,this.secretKey);
            AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
            ClientConfiguration clientConfig = new ClientConfiguration();
            if ("Y".equals(this.isHttps)) {
                clientConfig.setProtocol(Protocol.HTTPS);
            }else {
                clientConfig.setProtocol(Protocol.HTTP);
            }
            this.s3ObsClient = AmazonS3Client.builder()
                    .withEndpointConfiguration(endpointConfiguration)
                    .withClientConfiguration(clientConfig)
                    .withCredentials(credentialsProvider)
                    .disableChunkedEncoding()
                    .build();
        }
    }

    /**
     * 关闭阿里oss客户端
     */
    @Override
    public void closeClient() {
        if (s3ObsClient != null) {
            s3ObsClient.shutdown();
        }
    }

    /**
     * 上传资源文件-通过本地文件进行上传
     * @param objectKey
     * @param file
     * @return
     */
    @Override
    public boolean uploadRsm(String objectKey, File file) {
        int fileNum = objectKey.lastIndexOf("/");
        String fileName = "";
        if (fileNum >= 0) {
            fileName = objectKey.substring(fileNum + 1);
        }else {
            fileName = objectKey;
        }
        log.info("进入阿里巴巴SDK上传资源：[{}]",fileName);
        try (InputStream inputStream = new FileInputStream(file)) {
            ObjectMetadata metadata = new ObjectMetadata();
            //根据文件的名称判断文件的MIME类型
            String contentType = URLConnection.guessContentTypeFromName(file.getName());
            metadata.setContentType(contentType);
            metadata.setContentLength(inputStream.available());
            PutObjectResult putObjectResult = s3ObsClient.putObject(new PutObjectRequest(this.bucketName,objectKey,inputStream,metadata));
            if (putObjectResult != null && putObjectResult.getETag() != null) {
                log.info("上传文件成功：[{}]",putObjectResult.getETag());
            }else {
                log.error("文件上传失败过一会再上传一次");
                Thread.sleep(100);
                s3ObsClient.putObject(new PutObjectRequest(this.bucketName,objectKey,inputStream,metadata));
            }
        } catch (Exception e) {
           log.info(e.getMessage());
        }
        return true;
    }

    /**
     * 下载云文件资源
     * @param objectKey
     * @return
     */
    @Override
    public InputStream downloadRsm(String objectKey) {
        GetObjectRequest objectRequest = new GetObjectRequest(bucketName,objectKey);
        S3Object s3Object = s3ObsClient.getObject(objectRequest);
        if (s3Object != null) {
            return s3Object.getObjectContent();
        }
        return null;
    }

    /**
     * 获取资源的临时访问链接
     * @param objectKey
     * @return
     */
    @Override
    public String getRsmUrlWithAccess(String objectKey) {
        //设置此临时链接失效时间
        Date expiration = new Date(System.currentTimeMillis()+this.urlExpireSeconds);
        URL url = s3ObsClient.generatePresignedUrl(bucketName,objectKey,expiration, HttpMethod.GET);
        if (url != null) {
            return url.toString();
        }
        return "";
    }

    /**
     * 删除云资源文件
     * @param objectKey
     * @return
     */
    @Override
    public boolean deleteRsm(String objectKey) {
        try {
            //检查文件是否存在
            boolean isExist = s3ObsClient.doesObjectExist(this.bucketName,objectKey);
            if (isExist) {
                //要删除的文件存在 执行删除文件操作
                s3ObsClient.deleteObject(bucketName,objectKey);
            }else {
                log.info("删除文件不存在，无法删除文件");
            }
        } catch (Exception e) {
            //云资源文件可能不存在了
            log.error(e.getMessage());
        }
        return true;
    }
}
